/**
 * Admin Variable Script start
 */
var _editGridDefaultOption = {
		dataEvents:[
			{
				  "type":"blur"
				, "fn":function(e){ 
					var curGridId = $( e.target ).closest( "table[role=grid]" ).attr( 'id' );
					var curGridObj = $("#" + curGridId);
					
					var rowData = curGridObj.getRawData();
					
					rowData[ '' + e.target.name ] = $( e.target ).val();
					
					console.log( '[' + e.target.name + '][' + $( e.target ).val() + ']' );
					
					if( rowData.BBY_CRUD_STATUS != 'C' ){
						rowData.BBY_CRUD_STATUS = 'U';
					}
				}
			}
			, 
			{
				  "type":"focus"
				, "fn":function(e){ 
					var curGridId = $( e.target ).closest( "table[role=grid]" ).attr( 'id' );
					var curGridObj = $("#" + curGridId);
					
					var rowData = curGridObj.getRawData();
					
					rowData[ '' + e.target.name ] = $( e.target ).val();
					
					console.log( 'focus[' + e.target.name + '][' + $( e.target ).val() + ']' );
				}
			}
		]
	};

var _editGridButtons = [
		{
			caption:"Add", 
			buttonicon:"ui-icon-plus",//"ui-icon-newwin", 
			onClickButton: addGridRow, 
			position:"last",
			customClass:"menuMasked"
		}
		, {
			caption:"Del", 
			buttonicon:"ui-icon-trash",//"ui-icon-del", 
			onClickButton: deleteGridRow, 
			position:"last",
			customClass:"menuMasked"
		}
		, {
			caption:"Save", 
			buttonicon:"ui-icon-disk",//"ui-icon-del", 
			onClickButton: saveGridData, 
			position:"last",
			customClass:"menuMasked"
		}
	];
/**
 * Admin Variable Script end
 */

/**
 * Admin function Script start
 */
function addGridRow(){
	var rowData = {};
	var curGridObj = $(this);
	
	var parentGrid = curGridObj.jqGrid('getGridParam','parentGrid');
	var targetForm = curGridObj.jqGrid('getGridParam','targetForm');
	
	if(targetForm != null && targetForm != ''){
		var curInputList;
		var curFormObj;
		var curObjSearchOpt = [ 
			  ':input'
			//, ':select' 
		];
		for( var agri = 0; agri < curObjSearchOpt.length; agri++ ){
			curInputList = $("#" + targetForm + " " + curObjSearchOpt[ agri ] );
			if(curInputList != null){
				for( var ili = 0; ili < curInputList.length; ili++ ){
					curFormObj = $(curInputList[ ili ]);
					if( curFormObj.prop( 'name' ) != '' ){
						rowData[ curFormObj.prop( 'name' ) ] = '';
					}
				}
			}
		}
	}
	
	if(parentGrid != null && parentGrid != ''){
		parentGrid = $( '#' + parentGrid );
		rowData = $.extend(rowData, parentGrid.getRawData());
	}
	
	rowData = $.extend(rowData, curGridObj.jqGrid('getGridParam','defaultAddValue'));
	
	rowData.BBY_CRUD_STATUS = 'C';
	
	console.log( 'add rowData==================' );
	console.log(rowData);
	console.log( 'add rowData==================' );
	
	if(targetForm != null && targetForm != ''){
    	$("#" + targetForm ).bbyAdminBind({
    		bindObj: rowData
    		, bindGridObj:curGridObj
    	});
	}
	$(this).jqGrid('addRow', {initdata:rowData});
} 
function deleteGridRow(){
	var rowid = $(this).jqGrid('getGridParam','selrow');
	$(this).jqGrid('deleteRow', rowid );
}  
function saveGridData(){
	$(this).saveRawData();
}

function getGridSelectOption( pGroupCode ){
	return $.extend(true, {dataUrl:FULL_PATH + '/code/gridOptionCode.do?groupCode=' + pGroupCode}, _editGridDefaultOption);
}

function adminOnSelectRow( curGridObj, id ){
	
	//var curGridObj = $(this);
	
	console.log( 'adminOnSelectRow[' + id + ']' );
	
	var subGridList;
	var subGridId;
	var subGridObj;
	
	var searchParamObj = null;
	var currentRawData = null;
	
	var targetForm;
	
	curGridObj.editRow(id, true);
	
	currentRawData = curGridObj.getRawData();
	
	if(currentRawData.BBY_CRUD_STATUS != 'C'){
		var colModelList;
		var colModel;
		
		colModelList = curGridObj.jqGrid('getGridParam','colModel');
		
		for( var cmi = 0; cmi < colModelList.length; cmi++ ){
			colModel = colModelList[ cmi ];
			if(colModel.keyField == true){
				curGridObj.find( '#' + id + '_' + colModel.name ).attr( 'disabled', true );
				curGridObj.find( '#' + id + '_' + colModel.name ).attr( 'readOnly', true );
			}
		}
	}
	
	targetForm = curGridObj.jqGrid('getGridParam','targetForm');
	
	if(targetForm != null && targetForm != ''){
    	$("#" + targetForm ).bbyAdminBind({
    		bindObj: currentRawData
    		, bindGridObj:curGridObj
    	});
	}
	
	subGridList = curGridObj.jqGrid('getGridParam','subGridList');
	
	for( var sgi = 0; subGridList != null && sgi < subGridList.length; sgi++ ){
		subGridId = subGridList[ sgi ];
		subGridObj = $('#' + subGridId);
		subGridObj.jqGrid('clearGridData');
		
		
		searchParamObj = { datatype:'json' , postData:currentRawData };
		
		subGridObj.jqGrid( 'setGridParam', searchParamObj );
		subGridObj.trigger("reloadGrid", [{ current: true}]);
		
	}
}


/**
 * Admin function Script start
 */



/**
 * Admin plug in Script start
 */
(function ( $ ) {
	
	$.fn.bbyAdminBind = function(options) {
		var defaults = {
		};
		
		var opts = $.extend({}, defaults, options);
		
		var curFormObj = null;
		var formInputObj = null;
		var curGridObj = null;

		var jsonObj = opts.bindObj;
		var jsonCurStatus = jsonObj.BBY_CRUD_STATUS;
		
		curFormObj = $(this);
		//bindGridObj
		
		if(opts.bindGridObj != null){
			curGridObj = opts.bindGridObj;
		};
		
		this.setJsonData = function( pData ){
			jsonObj = pData;
			this.refreshForm();
		};
		
		//$('#excelSheetForm :input' )
		
		this.refreshForm = function (){
			
			jsonCurStatus = jsonObj.BBY_CRUD_STATUS;

			for (var jsonKey in jsonObj) {
				formInputObj = null;
				if (jsonObj.hasOwnProperty(jsonKey)) {
					
					if(
						jsonKey.indexOf( '_DATE' ) == ( jsonKey.length - 5 )
					){
						if( ( jsonObj[ jsonKey ] + '' ).length > 10){
							//DB date type value like [1407780255860] 	2014.08.17 by j4.choi
							if( !isNaN(jsonObj[ jsonKey ]) ) {
								jsonObj[ jsonKey ] = new Date(jsonObj[ jsonKey ]);

							} else {
								jsonObj[ jsonKey ] = ( jsonObj[ jsonKey ] + '' ).substring( 0, 10 );
								var dateStrArr = jsonObj[ jsonKey ].split( '-' );
								
								jsonObj[ jsonKey ] = dateStrArr[ 1 ] + '/' + dateStrArr[ 2 ] + '/' + dateStrArr[ 0 ];
							}
						} 
					}
					
					formInputObj = curFormObj.find("[name='" + jsonKey + "']");
					if(formInputObj.prop("tagName") == null || formInputObj.prop("tagName") == "undefined"){
						formInputObj = curFormObj.find("#" + jsonKey + ""); 
					}
					
					if(
						   jsonCurStatus == 'R' 
						&& formInputObj.prop( "type" ) != 'hidden'
					){
						formInputObj.attr( 'disable', true );
						formInputObj.attr( 'disabled', true );
						formInputObj.attr( 'readOnly', true );
					}
					
					if(
						   formInputObj.attr( "keyField" ) == 'true'
						|| formInputObj.attr( "keyField" ) == true
					){
						if( jsonCurStatus != 'C' ){
							formInputObj.attr( 'disable', true );
							formInputObj.attr( 'disabled', true );
							formInputObj.attr( 'readOnly', true );
						}else{
							formInputObj.attr( 'disable', false );
							formInputObj.attr( 'disabled', false );
							formInputObj.attr( 'readOnly', false );
						}
					}
					
					//console.log( "[" + jsonKey + "][" + jsonObj[ jsonKey ] + "][" + formInputObj.prop("tagName") + "]" );
					
					if( 
						   formInputObj.prop("tagName") == 'INPUT'
						|| formInputObj.prop("tagName") == 'SELECT'
						|| formInputObj.prop("tagName") == 'TEXTAREA'
					){
						
						if(jsonObj[ jsonKey ] != null 
							//&& jsonObj[ jsonKey ] != ''
								){
							
							formInputObj.val( jsonObj[ jsonKey ] );
							if(
								jsonKey.indexOf( '_DATE' ) == ( jsonKey.length - 5 )
							){
								if(formInputObj.val()){
									formInputObj.val("");
								}
							}
							
							formInputObj.attr( 'data-default', jsonObj[ jsonKey ] );
							formInputObj.val( jsonObj[ jsonKey ] );
						}
						
						if(formInputObj.prop("tagName") == 'SELECT'){
							
							//formInputObj.attr( 'data-default', jsonObj[ jsonKey ] );														
							try{
								formInputObj.select('setVal', jsonObj[ jsonKey ] );
							}catch(e){}
						}
						
						formInputObj.off('change');
						formInputObj.on('change', function () {
							var curInputObj = $(this);
							var curInputName = curInputObj.attr( 'name' );
							var curVal = curInputObj.val();
							jsonObj[ curInputName ] = curVal;
							if( jsonObj.BBY_CRUD_STATUS != 'C' ){
								jsonObj.BBY_CRUD_STATUS = 'U';
							}
							if(curGridObj != null){
								var curRow = curGridObj.jqGrid('getGridParam','selrow');
								console.log(
									  '[' + curRow + ']'
									+ '[' + curInputName + ']'
									+ '[' + curVal + ']'
								);
								curGridObj.jqGrid('setCell', curRow, curInputName, curVal);
							}
						});
					}else if( 
						   formInputObj.prop("tagName") == 'DIV' 
						|| formInputObj.prop("tagName") == 'SPAN'
					){
							formInputObj.html( jsonObj[ jsonKey ] );
					}
				}
			}
			
		};
		
		this.refreshForm();
		
		
		return this.each(function(){$this = $(this);});
	};
	
	
	/**
	 * extend $.fn
	 */
	$.extend($.fn, {
		// jqGrid contruct with default options
		jqGridAdmin : function(options) {
			// JQGRID option
			var config = {
				mtype:"POST",
				datatype: 'local', //not load when create. 'json'
				ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
			   	viewrecords: true,
			   	rowNum: 30,
			   	rowList: [10,20,30,40],
			    emptyrecords: "Data is Empty.",
			   	forceFit:true,
			    autowidth:true
			};
			
			return $(this).jqGridf($.extend(config, options));
		},
		// jqGrid contruct with default options with no paging
		jqGridAdminOnlyButton : function(options) {
			
			// JQGRID option
			var config = {
				url:CONTEXT_PATH + '/admin/retrieveAdminGridNoPagingData.json',
				saveURL:CONTEXT_PATH + '/admin/saveAdminData.json',
				serializeGridData: function (postData) {			
					postData = $.extend(postData, $(this).jqGrid('getGridParam','defaultSearchValue'));
					postData.selectQuery = $(this).jqGrid( 'getGridParam', 'selectQuery'  );
				    return JSON.stringify(postData);
				},
				jsonReader : {
					root: "rows",
					page: "page",
					total: "total",
					records: "records",
					repeatitems: false,
					cell: "cell",
					id: "id"
				},
				rowNum:-1,
				pgbuttons: false,     // disable page control like next, back button
				pgtext: '',         // disable pager text like 'Page 0 of 10'
				viewrecords: false,    // disable current view record text like 'View 1-10 of 100' 
				recordtext:'',
				rowList:[],
				beforeProcessing: function (data, status, xhr) {
					$(this).data( 'rawData', data.rows );
				} ,gridComplete : function(){
					$(this).setSelection( 1 );
				},
				onSelectRow: function(id){
					adminOnSelectRow( $(this), id );
				}
			};
			
			return $(this).jqGridAdmin($.extend(config, options));
		}
	});	

}
)(jQuery);
/**
 * Admin plug in Script end
 */


